package com.scaffold.commons;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class NetworkUtil {
	
	public static Set<String> getServerAddrList(){
		Set<String> addressList = new TreeSet<String>();
		try{
			Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
			while(niList.hasMoreElements()){
				NetworkInterface ni = niList.nextElement();
				Enumeration<InetAddress> addrList = ni.getInetAddresses();
				while(addrList.hasMoreElements()){
					InetAddress addr = addrList.nextElement();
					if(addr instanceof Inet4Address) {//只做IPV4
						addressList.add(addr.getHostAddress());
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return addressList;
	}
	
	public static Map<String, String> getServerAddrMap(){
		Map<String, String> hostMap = new TreeMap<String, String>();
		try{
			Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
			while(niList.hasMoreElements()){
				NetworkInterface ni = niList.nextElement();
				Enumeration<InetAddress> addrList = ni.getInetAddresses();
				while(addrList.hasMoreElements()){
					InetAddress addr = addrList.nextElement();
					if(addr instanceof Inet4Address) {//只做IPV4
						hostMap.put(addr.getHostAddress(), addr.getHostName());
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return hostMap;
	}
	
	public Map<String, String> getMacAddressMap() {
		Map<String, String> macMap = new TreeMap<String, String>();
		try {
			Enumeration<NetworkInterface> el = NetworkInterface.getNetworkInterfaces();
			while (el.hasMoreElements()) {
				NetworkInterface ni = el.nextElement();
				byte[] mac = ni.getHardwareAddress();
				if (mac == null){
					continue;
				}
				StringBuilder builder = new StringBuilder();
				for (byte b : mac) {
					builder.append(hexByte(b));
					builder.append("-");
				}
				builder.deleteCharAt(builder.length() - 1);
				macMap.put(builder.toString(), ni.getName());
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return macMap;
	}

	private String hexByte(byte b) {
		String s = "000000" + Integer.toHexString(b);
		return s.substring(s.length() - 2);
	}
//	private static String getServerAddr(){
//	String[] searchList = new String[]{
//			"211.152", "61.152", "210.192", "172.22", "192.168"
//	};
//	Set<String> addrList = NetworkUtil.getServerAddrList();
//	log.warn("serverAddress:" + addrList);
//	for(String search: searchList){
//		for(String addr: addrList){
//			if(addr.startsWith(search)){
//				return addr;
//			}
//		}
//	}
//	return addrList.iterator().next();
//}
}
